/*
 BluetoothClient 
 
 Shows how to connect to a Serial Port Service 
 for example to a Bluetooth Radio to control an 
 Arduino o Wiring Board  
 
 GNU GPL
 Copyright (c) 2012 Marlon J. Manrique       
 http://www.marlonj.com 
 $Id$
*/

// Import the client/server and bluetooth library  
import com.marlonj.processing.aclientserver.*;
import com.marlonj.processing.abluetooth.*;

// Object to control the bluetooth 
ABluetooth bluetooth;

// The bluetooth device 
ABluetoothDevice bluetoothDevice;

// Name of the device to search 
String deviceName = "FireFly-D932";

// Serial Service UUID  
String uuid = "00001101-0000-1000-8000-00805F9B34FB"; 

// The message to show 
String statusMessage = "Touch the Screen to Discover Devices"; 

/**
 * Create the bluetooth library 
 */
void setup() {
  // Create the bluetoot library 
  bluetooth = new ABluetooth(this);

  // Align the text 
  textAlign(CENTER);  
}

/**
 * Draw the name and address of the bluetoot adapter
 */ 
void draw() {  
  // Clear the screen
  background(0);
  
  // Draw to time bigger the text 
  scale(2);
  
  // Show the status message 
  text(statusMessage, width/4, height/4);
}

/**
 * Start the discover devices 
 */
void mousePressed() {
  // Discover device and try to found the device
  // if the device is alredy found connect and send data   
  if(bluetoothDevice == null) {
    startSearching();
  } else {
    connect();
  }
}

/**
 * A device was found 
 *
 * @param device Information of the device 
 */
void deviceDiscovered(ABluetoothDevice device) {
  // Check the name of the device 
  if(device.name().equals(deviceName))
    bluetoothDevice = device;
  
  // Show the name of the device on screen   
  statusMessage = device.name();
}

/**
 * The discover service ended  
 */
void discoveryEnded() {
  // If the bluetooth device is already found 
  // show a message or try again 
  if(bluetoothDevice != null)
    statusMessage = "Device " + deviceName + " Found.";
  else 
    statusMessage = "Device " + deviceName + " not Found, try again" ;
}

/**
 * Start searching devices 
 */
void startSearching() {  
  // If the bluetooh is active try to find devices 
  if(bluetooth.isEnabled()) {
    bluetooth.discover();
    statusMessage = "Searching ...";
  } else {
    statusMessage = "Bluetooth Not Enable";    
  }
}

/**
 * Connect to the service and send data 
 */
void connect() {
    // Get the client to send and receive data
    statusMessage = "Open Connection"; 
    AClient client = bluetoothDevice.connect(uuid);
    
    // Open the connection
    client.connect();
 
    // Write some info
    statusMessage = "Sending data "; 
    client.write(1);
    
    // Close the connection and be ready to search again  
    statusMessage = "Connection closed";
    client.close();
    bluetoothDevice = null;
}
